<template>
  <div class="user">
    <van-cell title="头像" is-link @click="changeAvatar">
      <img :src="$baseUrl + userInfo.avatar" alt="" style="width:50px;height:50px;border-radius:50%;">
    </van-cell>
    <van-cell title="用户名" is-link>
      {{userInfo.username}}
    </van-cell>
    <van-cell title="电话号码" is-link @click="changePhone">
      {{userInfo.phone}}
    </van-cell>
    <van-cell title="账户余额" is-link to="/recharge">
      <div style="color:#fc4a1a">{{userInfo.money}}元</div>
    </van-cell>
    <van-cell title="密码" is-link @click="changePassword">
      ******
    </van-cell>

    <van-popup v-model="show" round position="bottom" style="box-sizing:border-box;"
      :style="{ height: '35%',padding:'20px' }">
      <div class="isChangePhone" v-if="isChangePhone">
        <div class="title">修改手机号码</div>
        <el-input v-model="newPhone" placeholder="请输入新手机号码" style=""></el-input>
        <van-button type="danger" size="large" round @click="updatePhone">确认修改</van-button>
      </div>
      <div class="isChangePassword" v-if="isChangePassword">
        <div class="title">修改密码</div>
        <el-input v-model="oldPassword" show-password placeholder="请输入原密码" type="password" style=""></el-input>
        <el-input v-model="newPassword" show-password placeholder="请输入新密码" style="" type="password"></el-input>
        <el-input v-model="surePassword" show-password placeholder="请确认密码" style="" type="password"></el-input>

        <van-button type="danger" size="large" round @click="updatePassword">确认修改</van-button>
      </div>
      <div class="isChangeAvatar" v-if="isChangeAvatar">
        <div class="title">更换头像</div>
        <el-upload class="avatar-uploader" :action="upload(userInfo.id)" :show-file-list="false" :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { updateUserInfo, goLogin, updateUserAvatar } from '@/request/api.js'
export default {
  data() {
    return ({
      imageUrl:'',
      file: null,
      fileList: [],
      isChangeAvatar: false,
      oldPassword: '',
      newPassword: '',
      surePassword: '',
      userInfo: {},
      show: false,
      isChangePhone: false,
      isChangePassword: false,
      newPhone: '',
      data: {
        id: localStorage.getItem('userId'),
        username: null,
        password: null,
        money: null,
        avatar: null,
        phone: null,
        sex: null
      }
    })
  },
  mounted() {
    this.getUserInfo()
  },
  methods: {
    upload(id){
      return this.$baseUrl + '/user/updateUserAvatar?id=' + id
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.$toast.success('更新头像成功!请重新登录')
      this.logout()
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    changeAvatar() {
      this.show = true
      this.isChangePassword = false
      this.isChangePhone = false
      this.isChangeAvatar = true
    },
    changePassword() {
      this.show = true
      this.isChangePassword = true
      this.isChangePhone = false
      this.isChangeAvatar = false
    },
    updatePassword() {
      if (this.oldPassword == '' || this.newPassword == '' || this.surePassword == '') {
        this.$toast.fail('输入不能为空!')
        return
      }
      if (this.newPassword != this.newPassword) {
        this.$toast.fail('俩次密码不一致!')
        return
      }
      let loginParams = { username: this.userInfo.username, password: this.oldPassword };
      goLogin(loginParams).then(res => {
        if (res.data) {
          this.data.password = this.newPassword
          updateUserInfo(this.data).then(res => {
            if (res.data) {
              this.logout()
            }
          })
        } else {
          this.$toast.fail('原密码错误!')
        }
      })
    },
    logout() {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.setItem('cartList', JSON.stringify([]))
      localStorage.setItem('isNewUser', false)
      this.$toast.success('退出登录成功！')
      this.$toast.success('修改信息成功,请重新登录!')
      this.$router.push('/admin')
    },
    updatePhone() {
      if (this.newPhone == this.userInfo.phone) {
        this.$toast.fail('手机号码相同')
        return
      }
      let phoneReg = /^1[3-9]\d{9}$/
      if (phoneReg.test(this.newPhone)) {
        this.data.phone = this.newPhone
        updateUserInfo(this.data).then(res => {
          if (res.data) {
            this.logout()
          }
        })
      } else {
        this.$toast.fail('手机号码格式错误')
        return
      }
    },
    changePhone() {
      this.show = true
      this.isChangePhone = true
      this.isChangePassword = false
      this.isChangeAvatar = false
    },
    getUserInfo() {
      this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
      this.file = this.$baseUrl + this.userInfo.avatar
      this.fileList.push({ url: this.file })
    }
  }
}
</script>

<style scoped>
  .el-upload{
    border:1px solid #fc4a1a;
  }
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.isChangeAvatar,
.isChangePhone,
.isChangePassword {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.isChangePhone .el-input {
  width: 300px;
  margin: 10px 0;
}

.van-cell {
  display: flex;
  align-items: center;
}

.user .van-cell__title {
  line-height: 50px;
}

.user {
  margin-top: 45px;
}
</style>